package model

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ RoleModel = (*customRoleModel)(nil)

type (
	// RoleModel is an interface to be customized, add more methods here,
	// and implement the added methods in customRoleModel.
	RoleModel interface {
		roleModel
		FindOneByRoleName(ctx context.Context, rowBuilder squirrel.SelectBuilder) (*Role, error)
		UpdateStatusById(ctx context.Context, id, status int64) error
	}

	customRoleModel struct {
		*defaultRoleModel
	}
)

func (c *customRoleModel) FindOneByRoleName(ctx context.Context, rowBuilder squirrel.SelectBuilder) (*Role, error) {

	query, values, err := rowBuilder.ToSql()
	if err != nil {
		return nil, err
	}

	var resp Role
	err = c.QueryRowNoCacheCtx(ctx, &resp, query, values...)
	switch {
	case err == nil:
		return &resp, nil
	case errors.Is(err, sqlx.ErrNotFound):
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (c *customRoleModel) UpdateStatusById(ctx context.Context, id, status int64) error {
	roleIdKey := fmt.Sprintf("%s%v", cacheRoleRoleIdPrefix, id)
	_, err := c.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where `id` = ?", c.table, "status=?")
		return conn.ExecCtx(ctx, query, status, id)
	}, roleIdKey)
	return err
}

// NewRoleModel returns a model for the database table.
func NewRoleModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) RoleModel {
	return &customRoleModel{
		defaultRoleModel: newRoleModel(conn, c, opts...),
	}
}
